<?php
/**
 * Author: Traveler
 * Time  : 2021/9/4 19:17
 */

namespace app\controller\crm\v1;


use app\ErrorCode;
use app\service\RoleService;
use sunshine\basic\RestController;
use sunshine\exceptions\ApiException;
use think\App;
use think\exception\ValidateException;
use think\Response;

class Role extends RestController
{
    /**
     * Role constructor.
     *
     * @param App         $app
     * @param RoleService $service
     */
    public function __construct(App $app, RoleService $service)
    {
        parent::__construct($app);
        $this->service = $service;
    }

    /**
     * 获取指定角色的菜单
     *
     * @param int $id 角色ID
     * @return Response
     */
    public function getMenus(int $id): Response
    {
        $menus = $this->service->getRoleMenus($id);

        return $this->json->api(ErrorCode::SUCCESS, $menus);
    }


    /**
     * 创建(重写)
     *
     * @param string|null $validate 验证器名称
     * @return Response
     */
    public function create(?string $validate = null): Response
    {
        // 使用数据验证
        return parent::create('RoleValidate.base');
    }

    /**
     * 修改(重写)
     *
     * @param int         $id       ID
     * @param string|null $validate 验证器名称
     * @return Response
     */
    public function update(int $id, ?string $validate = null): Response
    {
        // 使用数据验证
        return parent::update($id, 'RoleValidate.base');
    }

    /**
     * 分配权限
     *
     * @param int $id 角色ID
     * @return Response
     */
    public function assignPermission(int $id): Response
    {
        $data = $this->request->put();

        try {
            $this->validate($data, 'RoleValidate.assign');
        } catch (ValidateException $e) {
            throw new ApiException(is_string($e->getError()) ? ErrorCode::UNKNOWN_VALIDATE_MSG : $e->getError());
        }

        if (!$this->service->assignPermission($id, $data)) {
            throw new ApiException(ErrorCode::ASSIGN_PERMISSION_FAILED);
        }

        return $this->json->api(ErrorCode::SUCCESS);
    }
}